class PDFHelper{
    constructor(url, canvas, pageNum=1, pageRect=[0, 0, 1, 1], onPageRender = null){
        var self = this;
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');
        this.pageNum = pageNum;
        pdfjsLib.getDocument(pdfurl).promise.then((doc)=> {
            self.doc = doc;
            // self.pageCount = doc.numPages;
            this.renderPage(self.pageNum);
        });
        this.pageRendering = false;
        this.pageNumPending = null;
        this.onPageRender = onPageRender;
    }
    nextPage() {
        if (this.pageNum >= this.doc.numPages) {
            return;
        }
        this.pageNum++;
        this.renderPage(this.pageNum);
    }
    prevPage() {
        if (this.pageNum <= 1)
            return;
        this.pageNum --;
        this.renderPage(this.pageNum);
    }
    changePage(num) {
        if (num < 1 || num > this.doc.numPages) 
            return;
        this.pageNum = num;
        this.renderPage();
    }
    renderPage() {
        if (this.pageRendering) return;
        var num = this.pageNum;
        console.log(num);
        this.pageRendering = true;
        if (this.onPageRender) {
            this.onPageRender(this);
        }
        // 
        // Using promise to fetch the page
        var self = this;
        this.doc.getPage(num).then((page) => {
            var viewport = page.getViewport({ scale: 1 });
            var bufcan = document.createElement("canvas");

            bufcan.width = window.innerWidth;
            bufcan.height = window.innerHeight;

            var scale = Math.min(bufcan.width / viewport.width, bufcan.height / viewport.height);
            self.viewport = page.getViewport({ scale: scale });

            var bufctx = bufcan.getContext('2d');
            if (self.canvas.width != bufcan.width || self.canvas.height != bufcan.height) {
                self.canvas.width = bufcan.width;
                self.canvas.height = bufcan.height;
            }

            var renderTask = page.render({
                canvasContext: bufctx,
                viewport: self.viewport
            });

            renderTask.promise.then(() => {
                self.ctx.drawImage(bufcan, 0, 0);
                self.pageRendering = false;
                if (self.pageNum !== num) {
                    self.renderPage(self.pageNum);
                }
            });
        });
    }
}